//
//  SalesChangeViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/6/8.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "SalesChangeViewController.h"
#import "SixSalesTableViewCell.h"
#import "FiveSalesTableViewCell.h"
#import "ThirdSalesTableViewCell.h"
#import "FourSalesTableViewCell.h"
#import "ApplySalesViewController.h"
#import "LogisViewController.h"
#import "FirstTableViewCell.h"
@interface SalesChangeViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic,strong)UIAlertController *alertController;
@property (nonatomic ,strong) NSMutableArray *imagArry;
@property (nonatomic ,strong) NSMutableDictionary *detailDic;
@property (nonatomic ,strong) NSString * shipperCode;
@property (nonatomic ,strong) NSString * logisticCode;
@property (nonatomic ,strong) NSString *sellerId;

@end

@implementation SalesChangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"换货详情";
    [self.view addSubview:[self tableView]];
    [self loadSalesDetailData];
    // Do any additional setup after loading the view.
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH-64) style:UITableViewStyleGrouped];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=Gray_Color;
        //_tableView.contentSize=CGSizeMake(MainW, 735);
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.separatorStyle=0;
        [_tableView registerNib:[UINib nibWithNibName:@"SixSalesTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SixSalesTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"FiveSalesTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"FiveSalesTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"ThirdSalesTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ThirdSalesTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"FourSalesTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"FourSalesTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"FirstTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"FirstTableViewCell"];
    }
    return _tableView;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        FirstTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"FirstTableViewCell"];
        NSString *time=[self timeWithTimeIntervalString:self.detailDic[@"createdTime"]];
        cell.timeLabel.text=[NSString stringWithFormat:@"申请时间:%@",time];
        if ([self.detailDic[@"aftersalesStatus"] intValue]==1) {
            cell.resonView.hidden=NO;
            cell.resonLabel.text=[NSString stringWithFormat:@"%@",self.detailDic[@"sellerReason"]];
            //cell.resonLabel.text=self.detailDic[@"buyserReason"];
        }else{
            cell.resonView.hidden=YES;
        }
        switch ([self.detailDic[@"aftersalesStatus"] intValue]) {
            case 0:
            {
                cell.stauteLabel.text=MyString(@"申请已撤销");
            }
                break;
            case 1:
            {
                cell.stauteLabel.text=MyString(@"申请未通过");
            }
                break;
            case 2:
            {
                cell.stauteLabel.text=MyString(@"申请中");
            }
                break;
            case 3:
            {
                cell.stauteLabel.text=MyString(@"申请通过");
            }
                break;
            case 4:
            {
                cell.stauteLabel.text=MyString(@"卖家确认");
            }
                break;
            case 5:
            {
                cell.stauteLabel.text=MyString(@"换货备货");
            }
                break;
            case 6:
            {
                cell.stauteLabel.text=MyString(@"卖家发货");
            }
                break;
            case 7:
            {
                cell.stauteLabel.text=MyString(@"已完成");
            }
                break;
                
            default:
                break;
        }
        return cell;
    }else if (indexPath.section==1){
        FiveSalesTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"FiveSalesTableViewCell"];
        cell.userLabel.text=[NSString stringWithFormat:@"%@:%@",MyString(@"收货人"),self.detailDic[@"buyerAddress"][@"consigneeName"]];
        cell.numLabel.text=[NSString stringWithFormat:@"%@",self.detailDic[@"buyerAddress"][@"consigneePhone"]];
        cell.addressLabel.text=[NSString stringWithFormat:@"收货地址:%@%@",self.detailDic[@"buyerAddress"][@"area"],self.detailDic[@"buyerAddress"][@"detail"]];
        return cell;
    }else if (indexPath.section==2){
        ThirdSalesTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"ThirdSalesTableViewCell"];
        [cell.shopImag sd_setImageWithURL:[NSURL URLWithString:self.detailDic[@"itemBrief"][@"imageUrl"]] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
        cell.shopName.text=self.detailDic[@"itemBrief"][@"spuName"];
        cell.shopType.text=self.detailDic[@"itemBrief"][@"saleName"];
        cell.shupNum.text=[NSString stringWithFormat:@"%@:× %@",MyString(@"数量"),self.detailDic[@"itemBrief"][@"quantity"]];
        //cell.logistView.hidden=NO;
        cell.SalesNum.text=[NSString stringWithFormat:@"%@:%@",MyString(@"售后单号"),self.detailDic[@"aftersalesId"]];
        CGSize size=[cell.SalesNum.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14] }];
        cell.SalesNum.frame=CGRectMake(10, 149, size.width, 15);
        cell.btnClick.frame=CGRectMake(cell.SalesNum.bsg_right+5, 149, 40, 15);
        [cell.btnClick addTarget:self action:@selector(copyNumClick) forControlEvents:UIControlEventTouchUpInside];
        cell.proLabel.text=[NSString stringWithFormat:@"%@:%@",MyString(@"问题描述"),self.detailDic[@"buyerReason"]];
        cell.numLabel.text=[NSString stringWithFormat:@"%@:%@",MyString(@"申请数量"),self.detailDic[@"number"]];
        cell.timeLabel.text=[NSString stringWithFormat:@"%@:%@",MyString(@"申请时间"),self.detailDic[@"createdTime"]];
        self.imagArry =self.detailDic[@"images"];
        [cell creatPictureView:self.imagArry];
        cell.addressView.hidden=YES;
        return cell;
    }else{
        FourSalesTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"FourSalesTableViewCell"];
        [cell.conactBtn addTarget:self action:@selector(conactBtnCilck) forControlEvents:UIControlEventTouchUpInside];
        if ([self.detailDic[@"aftersalesStatus"] intValue]>=3) {
            cell.addressView.hidden=NO;
            cell.sellerName.text=[NSString stringWithFormat:@"收货人:%@",self.detailDic[@"sellerAddress"][@"consigneeName"]];
            cell.phoneLabel.text=[NSString stringWithFormat:@"%@",self.detailDic[@"sellerAddress"][@"consigneePhone"]];
            cell.addressLabel.text=[NSString stringWithFormat:@"收货地址:%@%@",self.detailDic[@"sellerAddress"][@"area"],self.detailDic[@"sellerAddress"][@"detail"]];
        }else{
            cell.addressView.hidden=YES;
        }
        switch ([self.detailDic[@"aftersalesStatus"] intValue]) {
            case 0:
            {
                cell.cancelBtn.hidden=YES;
            }
                break;
            case 1:
            {
                //                self.cancelBtn.layer.borderWidth=0.8;
                //                self.cancelBtn.layer.borderColor=TextColor6.CGColor;
                //                ViewRadius(self.cancelBtn, 2);
                //                self.sendBackBtn.layer.borderWidth=0.8;
                //                self.sendBackBtn.layer.borderColor=Red_Color.CGColor;
                //                self.sendBackBtn.hidden=YES;
                //                ViewRadius(self.sendBackBtn, 2);
                cell.sendBackBtn.hidden=NO;
                [cell.sendBackBtn setTitle:MyString(@"撤销申请") forState:UIControlStateNormal];
                [cell.sendBackBtn addTarget:self action:@selector(cancelApplyClick) forControlEvents:UIControlEventTouchUpInside];
                [cell.sendBackBtn setTitleColor:TextColor6 forState:UIControlStateNormal];
                cell.sendBackBtn.layer.borderWidth=0.8;
                cell.sendBackBtn.layer.borderColor=TextColor6.CGColor;
                ViewRadius(cell.sendBackBtn, 2);
                cell.cancelBtn.hidden=NO;
                [cell.cancelBtn setTitle:MyString(@"再次申请") forState:UIControlStateNormal];
                [cell.cancelBtn addTarget:self action:@selector(ConfirmMoneyClick:) forControlEvents:UIControlEventTouchUpInside];
                [cell.cancelBtn setTitleColor:Red_Color forState:UIControlStateNormal];
                cell.cancelBtn.layer.borderWidth=0.8;
                cell.cancelBtn.layer.borderColor=Red_Color.CGColor;
                ViewRadius(cell.cancelBtn, 2);
                
                //cell.statusLabel.text=@"很遗憾,您的申请未通过审核!";
            }
                break;
            case 2:
            {
                                cell.cancelBtn.hidden=NO;
                //                cell.statusLabel.text=@"申请核实中,请耐心等待...";
            }
                break;
            case 3:
            {
                [cell.sendBackBtn setTitle:MyString(@"撤销申请") forState:UIControlStateNormal];
                [cell.sendBackBtn addTarget:self action:@selector(cancelApplyClick) forControlEvents:UIControlEventTouchUpInside];
                [cell.sendBackBtn setTitleColor:TextColor6 forState:UIControlStateNormal];
                cell.sendBackBtn.layer.borderWidth=0.8;
                cell.sendBackBtn.layer.borderColor=TextColor6.CGColor;
                ViewRadius(cell.sendBackBtn, 2);
                
                cell.sendBackBtn.hidden=NO;
                cell.cancelBtn.hidden=NO;
                [cell.cancelBtn setTitle:MyString(@"确认寄回") forState:UIControlStateNormal];
                [cell.cancelBtn addTarget:self action:@selector(sendBackClick) forControlEvents:UIControlEventTouchUpInside];
                [cell.cancelBtn setTitleColor:Red_Color forState:UIControlStateNormal];
                cell.cancelBtn.layer.borderWidth=0.8;
                cell.cancelBtn.layer.borderColor=Red_Color.CGColor;
                ViewRadius(cell.cancelBtn, 2);
                //                cell.statusLabel.text=@"您的申请已通过,请尽快寄回!";
            }
                break;
            case 4:
            {
                cell.sendBackBtn.hidden=YES;
                cell.cancelBtn.hidden=YES;
                //                cell.statusLabel.text=@"卖家收货确认中,请耐心等待...";
            }
                break;
            case 5:
            {
                cell.sendBackBtn.hidden=YES;
                cell.cancelBtn.hidden=YES;
                //                cell.statusLabel.text=@"卖家收货确认中,请耐心等待...";
            }
                break;
            case 6:
            {
                
                [cell.cancelBtn setTitle:MyString(@"确认收货") forState:UIControlStateNormal];
                [cell.cancelBtn addTarget:self action:@selector(ConfirmMoneyClick:) forControlEvents:UIControlEventTouchUpInside];
                [cell.cancelBtn setTitleColor:Red_Color forState:UIControlStateNormal];
                cell.cancelBtn.layer.borderWidth=0.8;
                cell.cancelBtn.layer.borderColor=Red_Color.CGColor;
                ViewRadius(cell.cancelBtn, 2);
                cell.cancelBtn.hidden=NO;
                //                cell.statusLabel.text=@"卖家已发货,请确认查收!";
            }
                break;
            case 7:
            {
                
                cell.sendBackBtn.hidden=YES;
                cell.cancelBtn.hidden=YES;
            }
                break;
                
            default:
                break;
        }

        return cell;
    }
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if ([self.detailDic[@"aftersalesStatus"] intValue]==1) {
            return 110;
        }else{
            return 50;
        }
        
    }else if (indexPath.section==1){
        return 115;
    }else if (indexPath.section==2){
        return 358;
    }else{
        return 160;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
//撤销申请{
-(void)cancelApplyClick{
    //NSLog(<#NSString * _Nonnull format, ...#>)
    LXAlertView *alert= [[LXAlertView alloc]initWithTitle:nil message:@"确定要撤销申请吗?" cancelBtnTitle:MyString(@"取消") otherBtnTitle:MyString(@"确定") clickIndexBlock:^(NSInteger clickIndex) {
        if (clickIndex==1) {
            [self cancleApplyOperation];NSLog(@"确定");
        }
    }];
    [alert showLXAlertView];
    //    self.imagArry=[NSMutableArray arrayWithObjects:@"2",@"1",@"1", nil];
    //    [self.tableView reloadData];
}
-(void)loadSalesDetailData{
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    dic[@"aftersalesId"]=[NSString stringWithFormat:@"%@",self.aftersalesId];
    [self doHttpRequestWithApi:API_APPLYSALESDETAIL method:GET dic:dic successBlock:^(NSDictionary *dic) {
        self.detailDic=dic[@"data"];
        self.sellerId=[NSString stringWithFormat:@"%@",self.detailDic[@"sellerId"]];
        [self.tableView reloadData];
    }];
    
}
//复制内容到剪贴板
-(void)copyNumClick{
    [MBProgressHUD showSuccess:MyString(@"复制成功")];
    UIPasteboard*pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string=[NSString stringWithFormat:@"%@:%@",MyString(@"售后单号"),self.detailDic[@"buyerReason"]];
}
-(void)cancleApplyOperation{
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    dic[@"aftersalesId"]=[NSString stringWithFormat:@"%@",self.aftersalesId];
    [self doHttpRequestWithApi:API_APPLYSALESCANCLE method:GET dic:dic successBlock:^(NSDictionary *dic) {
        [self showToast:MyString(@"撤销成功")];
        [self popToLastController:0.5];
    }];
    
}
-(void)sendBackClick{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:MyString(@"请输入物流信息") preferredStyle:UIAlertControllerStyleAlert];
    self.alertController=alertController;
    NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:MyString(@"购买数量")];
    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:TextColor3 range:NSMakeRange(0, 7)];
    [alertControllerMessageStr addAttribute:NSFontAttributeName value:FontAndStyle14 range:NSMakeRange(0, 7)];
    [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
    //增加取消按钮；
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:MyString(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *userNameTextField = alertController.textFields.firstObject;
        
        UITextField *user = alertController.textFields.lastObject;
        
        
        self.logisticCode= userNameTextField.text;;
        //        if (self.shipperCode.length==0||self.logisticCode.length==0) {
        //            [self showToast:@"请填写物流信息"];
        //        }
        [self sendGoods];
        NSLog(@"用户名 = %@",user.text);
    }];
    [defaultAction setValue:Red_Color forKey:@"_titleTextColor"];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:MyString(@"取消") style:UIAlertActionStyleCancel handler:nil];
    [cancelAction setValue:[UIColor colorWithHexString:@"#e65103"] forKey:@"_titleTextColor"];
    [alertController addAction:defaultAction];
    [alertController addAction:cancelAction];
    //定义第一个输入框；
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = MyString(@"请输入物流单号(可不填!)");
        textField.keyboardType=UIKeyboardTypeDefault;
        textField.delegate=self;
        textField.tag=100;
        
    }];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"请输入物流名称(可不填!)";
        textField.keyboardType=UIKeyboardTypeNumberPad;
        textField.delegate=self;
        textField.tag=200;
    }];
    [self presentViewController:alertController animated:true completion:nil];
    //确认寄回
}
-(void)ConfirmMoneyClick:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:@"再次申请"]) {
        ApplySalesViewController *vc=[[ApplySalesViewController alloc]init];
        vc.goodsDic=[NSMutableDictionary dictionary];
        //vc.goodsDic=self.detailDic[@"itemBrief"];
        [vc.goodsDic setObject:self.detailDic[@"itemId"] forKey:@"itemId"];
        [vc.goodsDic setObject:self.detailDic[@"itemBrief"][@"imageUrl"] forKey:@"imageUrl"];
        [vc.goodsDic setObject:self.detailDic[@"itemBrief"][@"name"] forKey:@"name"];
        [vc.goodsDic setObject:self.detailDic[@"itemBrief"][@"number"] forKey:@"number"];
        vc.dataDic=self.detailDic;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([sender.titleLabel.text isEqualToString:@"确认收货"]){
        [self sureGoods];
    }
    
    //确认收货
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if (textField.tag==200) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        LogisViewController*vc=[[LogisViewController alloc]init];
        vc.styple=1;
        vc.logistBlock = ^(NSDictionary *dic) {
            NSLog(@"dic-----%@",dic);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self presentViewController:self.alertController animated:true completion:nil];
            });
            
            textField.text=dic[@"zhcnName"];
            self.shipperCode=dic[@"code"];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
//联系卖家
-(void)conactBtnCilck{
    [self loadImInfo:self.sellerId];
    
}
-(void)sureGoods{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    dic[@"aftersalesId"]=[NSString stringWithFormat:@"%@",self.aftersalesId];
    [self doHttpRequestWithApi:API_APPLYSALESRECIVE method:GET dic:dic successBlock:^(NSDictionary *dic) {
         [self loadSalesDetailData];
    }];
}
-(void)sendGoods{
   
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    dic[@"shipperCode"]=[NSString stringWithFormat:@"%@",self.shipperCode];
    dic[@"logisticCode"]=[NSString stringWithFormat:@"%@",self.logisticCode];
    dic[@"aftersalesId"]=[NSString stringWithFormat:@"%@",self.aftersalesId];
    [self doHttpRequestWithApi:API_APPLYSALESSEND method:GET dic:dic successBlock:^(NSDictionary *dic) {
        //[self showToast:@"操作成功"];
        [self loadSalesDetailData];
    }];
}
-(void)loadImInfo:(NSString *)merchantId{
    ///api/member/chat/info
    self.isShowDiag=NO;
    NSMutableDictionary*dic=[[NSMutableDictionary alloc]init];
    //dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    dic[@"merchantId"]=merchantId;
    [ self doHttpRequestWithApi:CHATINFO method:GET dic:dic successBlock:^(NSDictionary *dic) {
        EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:[NSString stringWithFormat:@"%@",self.sellerId] conversationType:EMConversationTypeChat];
        chatController.title=[NSString stringWithFormat:@"%@",dic[@"data"][@"nickname"]];
        [self.navigationController pushViewController:chatController animated:YES];
        NSLog(@"-------%@",dic);
    }];
}
@end
